﻿using log4net.Config;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Threading.Tasks;
using System.Web;
using DisconfClient;
using Ymatou.CommonService;
using Ymatou.ServiceCenter;
using Ymatou.User.Dto.Auth;
using YmtAuth.AppService;
using YmtAuth.Dto;
using YmtAuth.LogService;
using YmtAuth.Repository.MSSQL;
using YmtAuth.Web.Service;
using YmtSystem.CrossCutting;

namespace YmtAuth.Web
{
    public class Global : System.Web.HttpApplication
    {

        private void AsyncInitListen(bool isAsyncInitSuccess)
        {

            YmatouLoggingService.Debug("开始执行（异步）服务注册的结果处理函数: {0}", isAsyncInitSuccess);
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            var logPath = AppDomain.CurrentDomain.BaseDirectory + "Config\\log4net.config";
            XmlConfigurator.Configure(new System.IO.FileInfo(logPath));
            ApplicationLog.Debug("认证服务开始启动，已初始化log4net");
            AppServiceHost.Start();
            ApplicationLog.Debug("已注册路由,执行YmatouFramework.Start()");          
            YmatouFramework.Start();
            ApplicationLog.Debug("执行YmtAuthRoute.RegisterRoutes");
            YmtAuthRoute.RegisterRoutes();
            ApplicationLog.Debug("TaskScheduler.UnobservedTaskException");
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            ApplicationLog.Debug("LogTask.Instance.Start()");
            LogTask.Instance.Start();
            //注册登录安全处理流程
            ApplicationLog.Debug("LoginSafeVerify.RegisterSafeHandleFlow");
            UserSafeVerify.RegisterSafeHandleFlow();
            ApplicationLog.Debug("IpBlackListAppService.InitIpMatchBulackSpec()");
            BlackListAppService.InitIpMatchpec();
            RepositoryDependencies.ReisterRepository();

            //RPC初始化，修改于2016/7/8 by WESLEY
            ServiceRegisterManager.AsyncRpcInitListener += AsyncInitListen;
            ServiceRegisterManager.InitRpcAsync();
            //请将这个初始化的方法调用放在你应用的入口处
            ConfigManager.Init();
            ApplicationLog.Debug("认证服务启动成功");
        }

        void TaskScheduler_UnobservedTaskException(object sender, System.Threading.Tasks.UnobservedTaskExceptionEventArgs e)
        {
            e.SetObserved();
            ApplicationLog.Error("task error" + e.Exception.ToString());
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {
            var errror = Server.GetLastError();
            if (errror != null)
            {
                YmatouLoggingService.Error("url->{0},msg->{1}", HttpContext.Current.Request.Url.ToString(),
                    errror.ToString());
                var err =
                    ResponseData<Dictionary<LoginResponseCode, string>>.CreateFail(
                        new Dictionary<LoginResponseCode, string>
                        {
                            {LoginResponseCode.SystemInnerError, errror.ToString()}
                        }, lastErrorMessage: "server error");
                HttpContext.Current.ResposeJson(err, true);
            }
        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
            LogTask.Instance.Stop();
            YmatouFramework.Stop();
        }
    }
}
